import { Button, Col, Form, Input, InputNumber, message, Row, Select, Switch } from 'antd';
import React, { useState, useEffect, useRef } from 'react';
import FormItem from '../../../components/FormItem';
import services from '../../../services/api';
import { compare } from '../../../utils/compare';
import Question from '../../../components/Question';
import { connect } from 'react-redux';
import Conditions from './conditions';

const { TextArea } = Input;

function Add(props) {
  const {
    namelist_config_id,
    namelist_title,
    list_type,
    data_type,
    sync_type,
    data_limit = 3000,
    sync_file_path,
    sync_file_name,
    sync_file_suffix,
    status = 1,
    remark,
    fileds_mapping = {},
    sync_condition_expression,
  } = props.record || {};

  const [conditions, setConditions] = useState(props.sync_conditions || []);
  const [operator, setOperator] = useState([]);
  const conditionRef = useRef(null);

  useEffect(() => {
    if (props.actionType !== 'add') getDetail();
    getOperator();
  }, []);

  /**获取详情 */
  function getDetail() {
    services.nameListConfig.detail({ namelist_config_id: props.record.namelist_config_id }).then((res) => {
      if (res.code === 0) {
        props.form.setFieldsValue({
          namelist_title: res.data.namelist_title,
          list_type: res.data.list_type,
          data_type: res.data.data_type,
          sync_type: res.data.sync_type,
          data_limit: res.data.data_limit,
          sync_file_path: res.data.sync_file_path,
          sync_file_name: res.data.sync_file_name,
          sync_file_suffix: res.data.sync_file_suffix,
          remark: res.data.remark,
          status: res.data.status === 1,
          fileds_start_time: res.data.fileds_mapping.start_time,
          fileds_end_time: res.data.fileds_mapping.end_time,
          fileds_data_content: res.data.fileds_mapping.data_content,
          fileds_remark: res.data.fileds_mapping.remark,
          sync_condition_expression: res.data.sync_condition_expression,
        });
        setConditions([]); // 为poc mock改造
        // setConditions(res.data.sync_conditions || [])
      } else {
        message.error(res.msg);
      }
    });
  }

  function getOperator() {
    services.nameListConfig.operatorList().then((res) => {
      if (res.code === 0) {
        setOperator(res.data);
      } else {
        message.error(res.msg);
      }
    });
  }

  const handleSubmit = (e) => {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (!err) {
        const conditions = conditionRef.current.getValue();
        if (values.sync_condition_expression) {
          const reg = /([|]{2}|[&]{2}|[()])/g;
          const newExpress = values.sync_condition_expression.replace(reg, '-');
          const arr = newExpress.split('-');
          arr.forEach((item) => {
            if (item && Number(item) > conditions.length) {
              message.warn(`条件表达式序号${item}不存在`);
              throw `条件表达式序号${item}不存在`;
            }
          });
        } else {
          if (conditions.length > 0) {
            message.warn(`请输入条件表达式`);
            throw `请输入条件表达式`;
          }
        }
        const params = {
          namelist_title: values.namelist_title,
          list_type: values.list_type,
          data_type: values.data_type,
          sync_type: values.sync_type,
          data_limit: values.data_limit,
          sync_file_path: values.sync_file_path,
          sync_file_name: values.sync_file_name,
          sync_file_suffix: values.sync_file_suffix,
          remark: values.remark || null,
          status: values.status ? 1 : 2,
          fileds_mapping: {
            data_content: values.fileds_data_content,
            start_time: values.fileds_start_time || null,
            end_time: values.fileds_end_time || null,
            remark: values.fileds_remark || null,
          },
          sync_condition_expression: values.sync_condition_expression || null,
          sync_conditions: conditions.length > 0 ? conditions : null,
        };
        if (props.actionType === 'update') params.namelist_config_id = namelist_config_id;
        services.nameListConfig[props.actionType](params).then((data) => {
          if (data.code === 0) {
            message.success(data.msg);
            if (props.closeModal) {
              props.closeModal();
            }
          } else {
            message.error(data.msg);
          }
        });
      }
    });
  };

  const formItems1 = [
    {
      label: {
        label: '名单名称',
        className: 'tantuer-form-item tantuer-form-item-nowrap',
      },
      name: 'namelist_title',
      options: {
        initialValue: namelist_title,
        rules: [
          { required: true, message: '请输入' },
          { max: 128, message: '最长128个字符' },
          { pattern: /^[\u4E00-\u9FA5_a-zA-Z0-9]+$/, message: '限中英文数字下划线' },
        ],
      },
      component: (
        <Input placeholder='请输入' disabled={props.actionType !== 'add'} style={compare(props, 'namelist_title')} />
      ),
    },
    {
      label: {
        label: '名单类型',
        className: 'tantuer-form-item tantuer-form-item-nowrap',
      },
      name: 'list_type',
      options: {
        initialValue: list_type,
        rules: [{ required: true, message: '请选择' }],
      },
      component: (
        <Select style={compare(props, 'list_type')} placeholder='请选择' disabled={props.actionType !== 'add'}>
          {props.namelist_type.map((it) => {
            return (
              <Select.Option value={it.key} key={it.key}>
                {it.value}
              </Select.Option>
            );
          })}
        </Select>
      ),
    },
    {
      label: {
        label: '数据类型',
        className: 'tantuer-form-item tantuer-form-item-nowrap',
      },
      name: 'data_type',
      options: {
        initialValue: data_type,
        rules: [{ required: true, message: '请选择' }],
      },
      component: (
        <Select style={compare(props, 'data_type')} placeholder='请选择' disabled={props.actionType !== 'add'}>
          {props.namelist_data_type.map((it) => {
            return (
              <Select.Option value={it.key} key={it.key}>
                {it.value}
              </Select.Option>
            );
          })}
        </Select>
      ),
    },
  ];

  const formItems2 = [
    {
      label: {
        label: '同步类型',
        className: 'tantuer-form-item tantuer-form-item-nowrap',
      },
      name: 'sync_type',
      options: {
        initialValue: sync_type,
        rules: [{ required: true, message: '请选择' }],
      },
      component: (
        <Select style={compare(props, 'sync_type')} placeholder='请选择' disabled={props.actionType === 'detail'}>
          {props.sync_type.map((it) => {
            return (
              <Select.Option value={it.key} key={it.key}>
                {it.value}
              </Select.Option>
            );
          })}
        </Select>
      ),
    },
    {
      label: {
        label: '单次分页条数',
        className: 'tantuer-form-item tantuer-form-item-nowrap',
      },
      name: 'data_limit',
      options: {
        initialValue: data_limit,
        rules: [{ required: true, message: '请输入' }],
      },
      component: (
        <InputNumber
          min={1}
          max={9999}
          precision={0}
          disabled={props.actionType === 'detail'}
          style={compare(props, 'data_limit')}
        />
      ),
    },
    {
      label: {
        label: '同步文件路径',
        className: 'tantuer-form-item tantuer-form-item-nowrap',
      },
      name: 'sync_file_path',
      options: {
        initialValue: sync_file_path,
        rules: [{ required: true, message: '请输入' }, { max: 128, message: '最长128个字符' }],
      },
      component: (
        <Input placeholder='请输入' disabled={props.actionType === 'detail'} style={compare(props, 'sync_file_path')} />
      ),
    },
    {
      label: {
        label: '同步文件名称',
        className: 'tantuer-form-item tantuer-form-item-nowrap',
      },
      name: 'sync_file_name',
      options: {
        initialValue: sync_file_name,
        rules: [{ required: true, message: '请输入' }, { max: 128, message: '最长128个字符' }],
      },
      component: (
        <Input placeholder='请输入' disabled={props.actionType === 'detail'} style={compare(props, 'sync_file_name')} />
      ),
    },
    {
      label: {
        label: '同步文件后缀',
        className: 'tantuer-form-item tantuer-form-item-nowrap',
      },
      name: 'sync_file_suffix',
      options: {
        initialValue: sync_file_suffix,
        rules: [
          { required: true, message: '请输入' },
          { max: 128, message: '最长128个字符' },
          { pattern: /^[a-zA-Z]+$/, message: '限英文' },
        ],
      },
      component: (
        <Input
          placeholder='请输入'
          disabled={props.actionType === 'detail'}
          style={compare(props, 'sync_file_suffix')}
        />
      ),
    },
    {
      label: {
        label: '是否启用',
        className: 'tantuer-form-item tantuer-form-item-nowrap',
      },
      name: 'status',
      options: {
        valuePropName: 'checked',
        initialValue: status === 1 ? true : false,
        rules: [{ required: true, message: '请输入' }],
      },
      component: <Switch disabled={props.actionType === 'detail'} />,
    },
    {
      label: {
        label: '描述',
        className: 'tantuer-form-item tantuer-form-item-nowrap',
      },
      name: 'remark',
      options: {
        initialValue: remark,
        rules: [{ max: 256, message: '最长256个字符' }],
      },
      component: (
        <TextArea
          placeholder='请输入'
          disabled={props.actionType === 'detail'}
          style={{ ...compare(props, 'remark') }}
        />
      ),
    },
  ].filter(Boolean);

  const formItems3 = [
    {
      label: {
        label: '开始时间列',
        className: 'tantuer-form-item tantuer-form-item-nowrap',
      },
      name: 'fileds_start_time',
      options: {
        initialValue: fileds_mapping.start_time,
      },
      component: (
        <InputNumber
          min={0}
          max={999}
          precision={0}
          disabled={props.actionType === 'detail'}
          style={compare(props, 'fileds_mapping', 'start_time')}
        />
      ),
    },
    {
      label: {
        label: '结束时间列',
        className: 'tantuer-form-item tantuer-form-item-nowrap',
      },
      name: 'fileds_end_time',
      options: {
        initialValue: fileds_mapping.end_time,
      },
      component: (
        <InputNumber
          min={0}
          max={999}
          precision={0}
          disabled={props.actionType === 'detail'}
          style={compare(props, 'fileds_mapping', 'end_time')}
        />
      ),
    },
    {
      label: {
        label: '同步字段列',
        className: 'tantuer-form-item tantuer-form-item-nowrap',
      },
      name: 'fileds_data_content',
      options: {
        initialValue: fileds_mapping.data_content,
        rules: [{ required: true, message: '请输入' }],
      },
      component: (
        <InputNumber
          min={0}
          max={999}
          precision={0}
          disabled={props.actionType === 'detail'}
          style={compare(props, 'fileds_mapping', 'data_content')}
        />
      ),
    },
    {
      label: {
        label: '字段描述列',
        className: 'tantuer-form-item tantuer-form-item-nowrap',
      },
      name: 'fileds_remark',
      options: {
        initialValue: fileds_mapping.remark,
      },
      component: (
        <InputNumber
          min={0}
          max={999}
          precision={0}
          disabled={props.actionType === 'detail'}
          style={compare(props, 'fileds_mapping', 'remark')}
        />
      ),
    },
  ];

  const expressionValidator = (rule, value, callback) => {
    if (value) {
      const reg = /^[0-9(]([|]{2}|[&]{2}|[0-9()])*$/;
      const endReg = /[0-9)]$/;
      const errReg = /(\(&)|(\(\|)|(&\))|(\|\))|(\)\()|(\d\()|(\)\d)|(&\|)|(\|&)|(\(\))/;
      if (!reg.test(value) || !endReg.test(value) || errReg.test(value)) {
        callback('非法字符，请检查后重新输入');
      }
      const lReg = /\(/g;
      const rReg = /\)/g;
      const lArr = value.match(lReg) || [];
      const rArr = value.match(rReg) || [];
      if (lArr.length !== rArr.length) {
        callback('非法字符，请检查后重新输入');
      }
    }
    callback();
  };

  const formItems4 = [
    {
      label: {
        label: '条件表达式',
        className: 'tantuer-form-item2 tantuer-form-item-nowrap',
      },
      name: 'sync_condition_expression',
      options: {
        initialValue: sync_condition_expression,
        rules: [{ validator: expressionValidator }],
      },
      component: (
        <Input
          placeholder='条件序号&&条件序号||条件序号，如1&&2||3'
          disabled={props.actionType === 'detail'}
          style={compare(props, 'sync_condition_expression')}
        />
      ),
      after: (
        <Question
          title={
            <div>
              <p>1.每个条件都有一个 Bool 值，管理员可以通过自定义的表达式进行组合，并根据组合结果，来设置动作；</p>
              <p>2.条件之间且关系用“&&”标识，或关系用“||”标识；</p>
              <p>3.表达式只允许输入条件序号代表各条件；</p>
              <p>4.表达式支持输入英文括号“()”来标识执行顺序</p>
            </div>
          }
        />
      ),
    },
  ];
  return (
    <div className='tantuer-form'>
      <Form onSubmit={() => false} className='login-form'>
        <div className='tantuer-field-area'>
          <div className='form-title'>基本信息</div>
          <Row type='flex' gutter={20}>
            {formItems1.map((item) => {
              return (
                <Col span={12} key={item.name}>
                  <FormItem {...props} form={props.form} item={item} colNum={1} />
                </Col>
              );
            })}
            <Col span={24}>
              <div className='form-title'>同步配置</div>
            </Col>
            {formItems2.map((item) => {
              return (
                <Col span={12} key={item.name}>
                  <FormItem {...props} form={props.form} item={item} colNum={1} />
                </Col>
              );
            })}
            <Col span={24}>
              <div className='form-title'>条件配置</div>
            </Col>
            {formItems3.map((item) => {
              return (
                <Col span={12} key={item.name}>
                  <FormItem {...props} form={props.form} item={item} colNum={1} />
                </Col>
              );
            })}
            <Col span={3}>执行条件：</Col>
            {formItems4.map((item) => {
              return (
                <Col span={12} key={item.name}>
                  <FormItem {...props} form={props.form} item={item} colNum={1} />
                </Col>
              );
            })}
            <Conditions sync_conditions={conditions} form={props.form} operator={operator} createRef={conditionRef} />
          </Row>
        </div>
        {props.actionType === 'detail' ? (
          ''
        ) : (
          <div className='form-btn'>
            <Button type='primary' onClick={handleSubmit} className='login-form-button' autoFocus={true}>
              确定
            </Button>
            <Button className='login-form-button' onClick={() => props.closeModal && props.closeModal(true)}>
              取消
            </Button>
          </div>
        )}
      </Form>
    </div>
  );
}

function mapStateToProps(state) {
  return {
    namelist_type: state.code.namelist_type || [],
    namelist_data_type: state.code.namelist_data_type || [],
    sync_type: state.code.sync_type || [],
  };
}
export default connect(mapStateToProps)(Form.create()(Add));
